/** @file    FormPlayerAudio.cpp
 *  @author  Alessandro Polo
 *  @version $Id: FormPlayerAudio.cpp 2558 2010-05-27 00:45:22Z alex $
 *  @brief
 * File containing methods for the wosh::gui::FormPlayerAudio class.
 * The header for this class can be found in FormPlayerAudio.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/
 
 #include "FormPlayerAudio.h"
 #include "ui_FormPlayerAudio.h"
 #include <interfaces/devices/PlayerAudio.h>

 #include <core/DeviceManager.h>
 #include <framework/gui/WidgetFileSelector.h>
 #include <QUrl>


using namespace std;
namespace wosh {
 namespace gui {

 WOSH_REGISTER(wosh::gui::FormPlayerAudio, "wosh::gui::IWidgetGeneric", 1.0, _static_FormPlayerAudio )
 WOSH_GUI_MAP(wosh::gui::FormPlayerAudio, "wosh::interfaces::devices::PlayerAudio", 0.0, _static_Map_FormPlayerAudio )

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

FormPlayerAudio::FormPlayerAudio(QWidget *parent) : IWidgetGeneric(parent)
 {
	this->m_ui = new Ui::FormPlayerAudio();
	this->m_ui->setupUi(this);

	this->setAcceptDrops(true);

	this->getWidgetURI().setName( Utilities::format("FormPlayerAudio#%10lu", Utilities::randomLong()) );

	connect(this->m_ui->tableView, SIGNAL(updated()), this->m_ui->wUpBarPlayList, SLOT(sayReady()));
	connect(this->m_ui->wUpBarPlayList, SIGNAL(updateClicked()), this, SLOT(refreshPlayList()));

	this->propMapper = new PropertiesMapper(this);
	this->propMapper->getMap().insert(_Player_KEY_Volume, this->m_ui->sliderVolume);
	this->propMapper->getMap().insert(_Player_KEY_Mute, this->m_ui->chkMuted);
	this->propMapper->getMap().insert(_Player_KEY_State, this->m_ui->lblState);
	this->propMapper->getMap().insert(_Player_KEY_CurrentFile, this->m_ui->lblMediaURI);
	this->propMapper->getMap().insert(_Player_KEY_CurrentPosition, this->m_ui->lblMediaPosition);
	this->propMapper->getMap().insert(_Player_KEY_CurrentLength, this->m_ui->lblMediaLength);

	mapMethodButton(_Player_METHOD_clear, this->m_ui->btnClear);
	mapMethodButton(_Player_METHOD_play, this->m_ui->btnPlay);
	mapMethodButton(_Player_METHOD_stop, this->m_ui->btnStop);

	mapMethodButton(_Player_METHOD_first, this->m_ui->tBtnTrackFirst);
	mapMethodButton(_Player_METHOD_last, this->m_ui->tBtnTrackLast);
	mapMethodButton(_Player_METHOD_next, this->m_ui->tBtnTrackNext);
	mapMethodButton(_Player_METHOD_prev, this->m_ui->tBtnTrackPrev);


	connect(this->m_ui->btnPlayFile, SIGNAL(clicked()), this, SLOT(btnPlayFile_clicked()));
	connect(this->m_ui->btnEnqueue, SIGNAL(clicked()), this, SLOT(btnEnqueue_clicked()));
	connect(this->m_ui->btnRefresh, SIGNAL(clicked()), this, SLOT(refreshAll()));
	connect(this->m_ui->btnRemove, SIGNAL(clicked()), this, SLOT(btnRemove_clicked()));
	connect(this->m_ui->chkMuted, SIGNAL(clicked()), this, SLOT(chkMuted_clicked()));
	connect(this->m_ui->tableView, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(tableView_doubleClicked(const QModelIndex&)));

	this->m_ui->sliderVolume->setTracking(false);
	connect(this->m_ui->sliderVolume, SIGNAL(sliderReleased()), this, SLOT(sliderVolume_sliderReleased()));


	this->menuSynch = new QMenu(this);
	this->menu_Players = new WidgetQMenu(this);
	this->menu_Players->setTitle( tr("From..") );
	this->menu_Players->setRequestMethod( _DeviceManager_METHOD_GetListByType );
	this->menu_Players->setRequestArgument( new Variant(_PlayerAudio_TYPE) );
	this->menu_Players->getTargetURI().setKernelName("*");
	this->menu_Players->getTargetURI().setName("Devices");
	this->menuSynch->addMenu(this->menu_Players);
	this->menu_Players->refreshAll();
	this->m_ui->tBtnSynch->setMenu( this->menuSynch );
	connect(this->menu_Players, SIGNAL( triggeredItem( WidgetQMenuItem* ) ), this, SLOT(menuSynch_triggeredItem( WidgetQMenuItem* )));

 }

FormPlayerAudio::~FormPlayerAudio()
 {
	delete this->propMapper; this->propMapper = NULL;
	delete this->m_ui;
 }

//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormPlayerAudio::changeEvent(QEvent *e)
 {
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
 }

void FormPlayerAudio::dragEnterEvent(QDragEnterEvent *e)
 {
//    if (e->mimeData()->hasFormat("text/plain"))
	e->acceptProposedAction();
 }

void FormPlayerAudio::dropEvent(QDropEvent *e)
 {
	if ( e->mimeData()->urls().empty() ) return;
	if ( e->mimeData()->urls().size() == 1 ) {
		string fixedUri = e->mimeData()->urls().at(0).toString().toStdString();
		if ( fixedUri.find("file:///") == 0 ) {
			fixedUri = fixedUri.substr(8);
			FilePath fp;
			FilePath::toLocalPath(fixedUri);
			fp.fromLocalPath(fixedUri);
			fixedUri = fp.getPath();
		 }
		executeRemoteMethod( _Player_METHOD_play, fixedUri );
		this->m_ui->wUpBarPlayList->showMessage( tr("Enqueuing %1..").arg(fixedUri.c_str()) );
	 }
	else {
		List* dl = new List();
		for(int i=0; i<e->mimeData()->urls().size(); i++) {
			string fixedUri = e->mimeData()->urls().at(i).toString().toStdString();
			if ( fixedUri.find("file:///") == 0 ) {
				fixedUri = fixedUri.substr(8);
				FilePath fp;
				FilePath::toLocalPath(fixedUri);
				fp.fromLocalPath(fixedUri);
				fixedUri = fp.getPath();
			 }
			dl->push_back<Variant>( fixedUri );
		 }
		executeRemoteMethod( _Player_METHOD_enqueue, dl );
		this->m_ui->wUpBarPlayList->showMessage( tr("Enqueuing %1 files..").arg(e->mimeData()->urls().size()) );
	 }
    e->acceptProposedAction();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormPlayerAudio::refreshAll() {
	refreshPlayList();
	refreshProperties();
 }

void FormPlayerAudio::refreshPlayList() {
	executeRemoteMethod( _METHOD_List );
	this->m_ui->wUpBarPlayList->sayRetrieving();
 }

void FormPlayerAudio::refreshProperties() {
	executeRemoteMethod( _METHOD_ListProperties );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormPlayerAudio::btnPlayFile_clicked()
 {
	WidgetFileSelector* fSel = new WidgetFileSelector();
	fSel->setWindowTitle( tr("Select (Audio) Target..") );
	fSel->setRootPath("$MUSIC");
	//fSel->setTargetPattern("*.mp3");
	if ( fSel->exec() == QDialog::Accepted ) {
		executeRemoteMethod( _Player_METHOD_play, fSel->getItemPath().getPath() );
		this->m_ui->wUpBarPlayList->showMessage( tr("Playing %1..").arg(fSel->getItemPath().getPath().c_str()) );
	 }
	delete fSel;
 }

void FormPlayerAudio::btnEnqueue_clicked()
 {
	WidgetFileSelector* fSel = new WidgetFileSelector();
	fSel->setWindowTitle( tr("Select (Audio) Target..") );
	fSel->setRootPath("$MUSIC");
	//fSel->setTargetPattern("*.mp3");
	if ( fSel->exec() == QDialog::Accepted ) {
		executeRemoteMethod( _Player_METHOD_enqueue, fSel->getItemPath().getPath() );
		this->m_ui->wUpBarPlayList->showMessage( tr("Enqueuing %1..").arg(fSel->getItemPath().getPath().c_str()) );
	 }
	delete fSel;
 }


void FormPlayerAudio::btnRemove_clicked()
 {
	int index = this->m_ui->tableView->getCurrentItemAsVariantAtCol( 0 ).toInteger(-1);
	if ( index < 0 ) {
		return;
	 }
	executeRemoteMethod( _Player_METHOD_remove, index );
	this->m_ui->wUpBarPlayList->showMessage( tr("Removing #%1").arg(index) );
 }

void FormPlayerAudio::chkMuted_clicked() {
	executeRemoteMethod( _Player_METHOD_set_mute, Variant(this->m_ui->chkMuted->isChecked()) );
 }

void FormPlayerAudio::sliderVolume_sliderReleased() {
	executeRemoteMethod( _Player_METHOD_set_volume, Variant(this->m_ui->sliderVolume->value()) );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormPlayerAudio::tableView_doubleClicked( const QModelIndex& )
 {
	int itemIndex = this->m_ui->tableView->getCurrentItemAsVariantAtCol( 0 ).toInteger(-1);

	executeRemoteMethod( _Player_METHOD_play_index, itemIndex );
	this->m_ui->wUpBarPlayList->showMessage( tr("Playing #%1").arg(itemIndex) );
 }

void FormPlayerAudio::menuSynch_triggeredItem( WidgetQMenuItem* item ) {
	if ( item == NULL ) return;
	Request* request_command = new Request( _Player_METHOD_synch, new Variant(this->getTargetURI().toString()) );
	Message* message = new Message(request_command);
	message->setDestination( item->getRemoteURI() );
	postMessageForTarget(message);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormPlayerAudio::busMessage( const Message& message, const Bus* ) {
	if ( message.isEmpty() || !message.getContent()->isResponse() ) return;
	if ( !isMessageForMeOrFromTarget(message) ) return;
	const wosh::Response* response = message.getContent()->asResponse();

	this->propMapper->evalResponse(response);
	this->m_ui->tableView->evalResponse(response);

	promptMethodResponse(message);
 }

/*
	else if ( response->getMethod() == _METHOD_SetProperty ) {
		if ( !response->hasData() )
			return;
	 }
	else if ( response->getMethod() == _Player_METHOD_set_volume ) {
		if ( WSUCCEEDED(response->getReturnValue()) ) {
			this->m_ui->sliderVolume->setToolTip( tr("Volume %1").arg(this->m_ui->sliderVolume->value()) );
		 }
		else {
			refreshPlayList();
			QMessageBox::warning(this, this->windowTitle(), tr("ERROR#%1 Cleaning Playlist").arg(response->getReturnValue()) );
		 }
	 }
	else if ( response->getMethod() == _Player_METHOD_clear ) {
		if ( WSUCCEEDED(response->getReturnValue()) ) {
			this->wTableModel->loadTable(NULL);
			this->m_ui->tableView->reset();
			this->m_ui->wUpBarPlayList->showMessage( tr("PlayList has been cleaned.") );
		 }
		else {
			refreshProperties();
			QMessageBox::warning(this, this->windowTitle(), tr("ERROR#%1 Cleaning Playlist").arg(response->getReturnValue()) );
		 }
	 }
	else if ( response->getMethod() == _Player_METHOD_play || response->getMethod() == _Player_METHOD_enqueue ) {
		refreshAll();
		if ( WSUCCEEDED(response->getReturnValue()) ) {
			this->m_ui->wUpBarPlayList->showMessage( tr("PlayList has been updated.") );
		 }
		else {
			QMessageBox::warning(this, this->windowTitle(), tr("ERROR#%1 Updating Playlist").arg(response->getReturnValue()) );
		 }
	 }
	else if ( response->getMethod() == _Player_METHOD_first || response->getMethod() == _Player_METHOD_last ||
			  response->getMethod() == _Player_METHOD_next || response->getMethod() == _Player_METHOD_prev ) {
		refreshProperties();
		if ( WFAILED(response->getReturnValue()) ) {
			QMessageBox::warning(this, this->windowTitle(), tr("ERROR#%1 Updating Playlist").arg(response->getReturnValue()) );
		 }
	 }
*/

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace gui
}; // namespace wosh
